<?php

namespace App\Http\Controllers\Api;

use App\Models\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class MembersController extends Controller
{
    public function store(Request $request)
    {

        $validator =  Validator::make($request->all(), [
            'name' => 'required',
            'branch_id' => 'required',
            'username' => 'required|unique:members',
            'password' => 'required',
            'openid' => 'required',
            'avatar' => 'required',
            'nickname' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors());
        }
        $member = new Member();
        $member->fill($request->all());//变量填充
        $member->save();//变量存储数据

        return response()->json(['status' => true, 'createId' => $member->id ])->setStatusCode(201);
    }
    public function update(Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'username' => [
                'required',
                Rule::unique('members')->ignore($request->openid,'openid'),
            ],
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors());
        }
        $member=Member::where('openid',$request->openid)->first();
        $member->fill($request->all());//变量填充
        $member->state=0;
        $member->save();//变量存储数据

        return response()->json(['status' => true, 'updateId' => $member->id ])->setStatusCode(201);
    }
    public  function findMan()
    {
        return response()->json(Member::all());

    }
}
